package com.lx.Login.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lx.Login.bean.LoginPropertise;
import com.lx.bean.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    LoginPropertise propertise;

    ObjectMapper objectMapper = new ObjectMapper();


    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = (HttpSession) request.getSession();
        Object myinfo = session.getAttribute(propertise.getSessionKey());
        if (myinfo == null) {
            String accept = request.getHeader("Accept");
            if (accept != null && accept.startsWith("application/json")) {
                // 如果是ajax请求, 返回result 提示未登录
                Result result = new Result(0, "请先登录系统", null);
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write(objectMapper.writeValueAsString(result));
            }else{
                // cart.html?id=2, requestURI=>cart.html, queryString=>id=2
                // 获取访问的页面地址
                String servletPath = request.getServletPath();
                session.setAttribute("goto", servletPath);
                // 如果是表单请求(xxx.html) 跳转到登录页
                response.sendRedirect("/login.html?cause=nologin");
            }

            return false;
        }
        return true;
    }
}
